#include "stdafx.h"
#include "Network.h"

#using <mscorlib.dll>
#using <system.dll>


namespace Safe {
	namespace Http
{
	
	HttpTimestampRequest::HttpTimestampRequest( BYTE* pbRequest, DWORD cbRequest ) {
		this->m_request = gcnew array<unsigned char,1>( cbRequest );
		System::Runtime::InteropServices::Marshal::Copy( (System::IntPtr)pbRequest, this->m_request, 0, cbRequest );
	}

	HttpTimestampRequest::HttpTimestampRequest( array<unsigned char>^ request ) { 
		m_request = gcnew array<unsigned char>( request->Length );
		request->CopyTo(m_request, 0);
	}

	HttpTimestampRequest::~HttpTimestampRequest() { 
	}

	array<unsigned char>^ HttpTimestampRequest::Submit(System::String^ url) { 
		
		System::Net::WebRequest^ req = System::Net::WebRequest::Create( gcnew System::Uri(url) );
		req->Method = "POST";
		req->ContentType = "application/timestamp-query";
		req->ContentLength = m_request->Length;
		System::IO::Stream^ reqStream = req->GetRequestStream();
		reqStream->Write(m_request, 0, m_request->Length);
		reqStream->Flush();

		System::Net::WebResponse^ resp = req->GetResponse();
		try { 
			System::IO::Stream^ respStream = resp->GetResponseStream();
			if( resp->ContentLength > 0 ) { 
				/// read the response until the number of bytes read is equal to the 
				/// content length
				System::Collections::Generic::List<unsigned char>^ rvalColl = gcnew System::Collections::Generic::List<unsigned char>((int)resp->ContentLength);
				array<unsigned char>^ buffer = gcnew array<unsigned char>( (int)resp->ContentLength );
				while( rvalColl->Count < resp->ContentLength )
				{
					int actuallyRead = respStream->Read( buffer, 0, buffer->Length );
					for( int i=0; i<actuallyRead; i++)
					{
						rvalColl->Add(buffer[i]);
					}
				}
				respStream->Close();
				return rvalColl->ToArray();
			} else { 
				/// keep reading until the response is closed, since the content length
				/// was not supplied in the HTTP headers
				System::IO::MemoryStream^ mOut = gcnew System::IO::MemoryStream();
				array<unsigned char>^ buf = gcnew array<unsigned char>( 5 * 1024 );
				int numRead = 1;
				while( 0 < numRead ) {
					numRead = respStream->Read( buf, 0, buf->Length);
					mOut->Write( buf, 0, numRead );
				}
				respStream->Close();
				return mOut->ToArray();
			}
		} finally { 
			resp->Close();
		}
	}


}
}